package com.xyht.sca_s.student_manage_system.modules.repairCheck.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.data.PictureRenderData;
import com.deepoove.poi.data.PictureType;
import com.deepoove.poi.data.Pictures;
import com.deepoove.poi.policy.PictureRenderPolicy;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.xyht.sca_s.student_manage_system.common.commonReturn.CommonCodeEnum;
import com.xyht.sca_s.student_manage_system.common.commonReturn.CommonResult;
import com.xyht.sca_s.student_manage_system.common.commonReturn.ExceptionCast;
import com.xyht.sca_s.student_manage_system.common.commonReturn.ResponseResult;
import com.xyht.sca_s.student_manage_system.common.util.ApiModelUtil;
import com.xyht.sca_s.student_manage_system.common.util.CacheUtil;
import com.xyht.sca_s.student_manage_system.common.util.TimeUtil;
import com.xyht.sca_s.student_manage_system.modules.carUseReturn.entity.SmsCarUseReturnApplication;
import com.xyht.sca_s.student_manage_system.modules.common.constant.FileSavePathConstant;
import com.xyht.sca_s.student_manage_system.modules.newTips.myEnum.AppTypeEnum;
import com.xyht.sca_s.student_manage_system.modules.newTips.myEnum.RangeTypeEnum;
import com.xyht.sca_s.student_manage_system.modules.newTips.myEnum.TipsTypeEnum;
import com.xyht.sca_s.student_manage_system.modules.newTips.util.NewTipsUtil;
import com.xyht.sca_s.student_manage_system.modules.repairCheck.entity.SmsRepairCheckApply;
import com.xyht.sca_s.student_manage_system.modules.repairCheck.entity.SmsRepairCheckDetail;
import com.xyht.sca_s.student_manage_system.modules.repairCheck.entity.SmsRepairCheckProcess;
import com.xyht.sca_s.student_manage_system.modules.repairCheck.entity.dto.*;
import com.xyht.sca_s.student_manage_system.modules.repairCheck.entity.vo.*;
import com.xyht.sca_s.student_manage_system.modules.repairCheck.mapper.SmsRepairCheckApplyMapper;
import com.xyht.sca_s.student_manage_system.modules.repairCheck.mapper.SmsRepairCheckDetailMapper;
import com.xyht.sca_s.student_manage_system.modules.repairCheck.mapper.SmsRepairCheckMpjMapper;
import com.xyht.sca_s.student_manage_system.modules.repairCheck.mapper.SmsRepairCheckProcessMapper;
import com.xyht.sca_s.student_manage_system.modules.repairCheck.service.SmsRepairCheckApplyService;
import com.xyht.sca_s.student_manage_system.modules.user.entity.SmsRole;
import com.xyht.sca_s.student_manage_system.modules.user.entity.SmsUser;
import com.xyht.sca_s.student_manage_system.modules.user.entity.SmsUserRoleRelation;
import com.xyht.sca_s.student_manage_system.modules.user.mapper.SmsRoleMapper;
import com.xyht.sca_s.student_manage_system.modules.user.mapper.SmsUserMapper;
import com.xyht.sca_s.student_manage_system.modules.user.mapper.SmsUserRoleRelationMapper;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.Future;
import java.util.stream.Collectors;

import static com.xyht.sca_s.student_manage_system.common.util.ParamCheckUtil.isNullOrEmpty;
import static com.xyht.sca_s.student_manage_system.modules.agreement.constant.agreementObjectTypeConstant.AGREEMENT_OBJECT_TYPE_PERSON;
import static com.xyht.sca_s.student_manage_system.modules.examinePaymentEquipment.constant.isExportProcessConstant.EXPORT_PROCESS_TRUE;
import static com.xyht.sca_s.student_manage_system.modules.examinePaymentEquipment.constant.paymentExamineStatusConstant.*;
import static com.xyht.sca_s.student_manage_system.modules.repairCheck.constant.ProcessNameConstant.*;
import static com.xyht.sca_s.student_manage_system.modules.repairCheck.constant.repairCheckApplicationTypeConstant.*;
import static com.xyht.sca_s.student_manage_system.modules.repairCheck.constant.repairCheckObjectTypeConstant.REPAIR_CHECK_OBJECT_TYPE_PERSON;
import static com.xyht.sca_s.student_manage_system.modules.repairCheck.constant.repairCheckObjectTypeConstant.REPAIR_CHECK_OBJECT_TYPE_ROLE;
import static com.xyht.sca_s.student_manage_system.modules.repairCheck.constant.repairCheckStatusConstant.*;
import static com.xyht.sca_s.student_manage_system.modules.student.constant.StudentInfoCommonConstant.PER_SHEET_NUM;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author XYHT
 * @since 2023-06-19
 */
@Service
public class SmsRepairCheckApplyServiceImpl extends ServiceImpl<SmsRepairCheckApplyMapper, SmsRepairCheckApply> implements SmsRepairCheckApplyService {
    @Resource
    private FileSavePathConstant fileSavePathConstant;
    @Autowired
    SmsRepairCheckApplyMapper smsRepairCheckApplyMapper;
    @Autowired
    NewTipsUtil newTipsUtil;
    @Autowired
    SmsRepairCheckProcessMapper smsRepairCheckProcessMapper;
    @Autowired
    SmsRepairCheckDetailMapper smsRepairCheckDetailMapper;
    @Autowired
    CacheUtil cacheUtil;
    @Autowired
    SmsRepairCheckMpjMapper smsRepairCheckMpjMapper;
    @Autowired
    SmsUserMapper smsUserMapper;

    @Autowired
    SmsRoleMapper smsRoleMapper;

    @Autowired
    private SmsUserRoleRelationMapper smsUserRoleRelationMapper;

    @Transactional
    @Override
    public ResponseResult repairCheck(SmsRepairCheckApplyVO applyVO, String user_id) {
        List<SmsRepairCheckProcess> fillProcessList =
                smsRepairCheckProcessMapper.selectList(new QueryWrapper<SmsRepairCheckProcess>()
                        .lambda()
                        .eq(SmsRepairCheckProcess::getProcessIsApplicationEdit, true)
                        .eq(SmsRepairCheckProcess::getProcessIsUse, true)
                        .orderByAsc(SmsRepairCheckProcess::getProcessSort));
        if (fillProcessList != null && fillProcessList.size() > 0) {
            if (applyVO.getProcessList() == null || applyVO.getProcessList().size() < 1) {
                return CommonResult.failed(CommonCodeEnum.REPAIR_CHECK_ALLOW_USER_NOT_SETTING);
            }
            //判断申请人是否将全部需要编辑流程填写
            List<SmsRepairCheckProcess> filterList = fillProcessList
                    .stream()
                    .filter(process -> {
                                if (process.getProcessName().equals(PROCESS_NAME_LOGISTICS)) {
                                    List<String> result = applyVO.getProcessList()
                                            .stream()
                                            .filter(fillProcess -> fillProcess.getProcessId().equals(process.getId()))
                                            .map(SmsRepairCheckDetailVO::getId)
                                            .collect(Collectors.toList());
                                    //匹配的去除  未匹配的留下
                                    if (result.size() > 0) {
                                        return false;
                                    } else {
                                        return true;
                                    }
                                }
                                return false;
                            }
                    )
                    .collect(Collectors.toList());
            if (filterList.size() > 0) {
                return CommonResult.failed(CommonCodeEnum.REPAIR_CHECK_ALLOW_PROCESS_NOT_FILL);
            }
        }

        //创建申请表
        SmsRepairCheckApply addApplication = new SmsRepairCheckApply();
        BeanUtils.copyProperties(applyVO, addApplication);
        addApplication.setApplyUserId(user_id);
        addApplication.setAllowStatus(REPAIR_CHECK_STATUS_WAIT_ALLOW);
        QueryWrapper<SmsUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SmsUser::getId, user_id);
        SmsUser smsUser = smsUserMapper.selectOne(queryWrapper);
        addApplication.setApplyPerson(smsUser.getRealName());
        smsRepairCheckApplyMapper.insert(addApplication);

        if (addApplication.getId() == null) {
            ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.FAIL));
        }
        String application_id = addApplication.getId();

        //创建审批流程
        List<SmsRepairCheckProcess> originProcessList =
                smsRepairCheckProcessMapper.selectList(new QueryWrapper<SmsRepairCheckProcess>()
                        .lambda()
                        .eq(SmsRepairCheckProcess::getProcessIsUse, true)
                        .orderByAsc(SmsRepairCheckProcess::getProcessSort));
        if (originProcessList == null || originProcessList.size() < 1) {
            ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.REPAIR_CHECK_PROCESS_NOT_SETTING));
        }
        int sort = 1;
        for (SmsRepairCheckProcess process : originProcessList) {
            //判断管理员是否配置初始流程
            if (process.getProcessName().equals(PROCESS_NAME_LOGISTICS) && !process.getProcessIsApplicationEdit()) {
                if (isNullOrEmpty(process.getProcessObjectId()) || isNullOrEmpty(process.getProcessObjectType())) {
                    ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.REPAIR_CHECK_PROCESS_NOT_SETTING));
                }
            }
            SmsRepairCheckDetail addDetail = new SmsRepairCheckDetail();

            addDetail.setApplicationId(application_id);
            addDetail.setProcessId(process.getId());
            addDetail.setProcessIsSign(process.getProcessIsSign());
            addDetail.setProcessIsStamp(process.getProcessIsStamp());
            addDetail.setProcessName(process.getProcessName());
            addDetail.setDetailAllowStatus(REPAIR_CHECK_STATUS_WAIT_ALLOW);
            addDetail.setDetailSort(sort++);

            //申请人可编辑流程
            if (process.getProcessIsApplicationEdit()) {
                List<SmsRepairCheckDetailVO> filterList = applyVO.getProcessList()
                        .stream()
                        .filter(fillProcess -> fillProcess.getProcessId().equals(process.getId()))
                        .collect(Collectors.toList());
                if (filterList.size() < 1) {
                    ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.REPAIR_CHECK_ALLOW_PROCESS_NOT_FILL));
                }
                SmsRepairCheckDetailVO fillProcessReq = filterList.get(0);

                if (isNullOrEmpty(fillProcessReq.getProcessObjectId())) {
                    ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.INVALID_PARAM));
                }
                addDetail.setProcessObjectId(fillProcessReq.getProcessObjectId());
                addDetail.setProcessObjectType(REPAIR_CHECK_OBJECT_TYPE_PERSON);
            } else {
                addDetail.setProcessObjectId(process.getProcessObjectId());
                addDetail.setProcessObjectType(process.getProcessObjectType());
            }
            smsRepairCheckDetailMapper.insert(addDetail);
        }
        SmsRepairCheckDetail addDetail = new SmsRepairCheckDetail();
        addDetail.setDetailAllowUserId(user_id);
        addDetail.setProcessObjectType(REPAIR_CHECK_OBJECT_TYPE_PERSON);
        addDetail.setProcessObjectId(user_id);
        smsRepairCheckDetailMapper.update(addDetail,new LambdaQueryWrapper<SmsRepairCheckDetail>()
        .eq(SmsRepairCheckDetail::getApplicationId,application_id)
        .eq(SmsRepairCheckDetail::getProcessName,PROCESS_NAME_REPAIR));

        //消息通知
        //通知流程第一个节点
        SmsRepairCheckDetail firstDetail =
                smsRepairCheckDetailMapper.selectOne(new QueryWrapper<SmsRepairCheckDetail>()
                        .lambda()
                        .eq(SmsRepairCheckDetail::getApplicationId, application_id)
                        .eq(SmsRepairCheckDetail::getDetailSort, 1)
                        .orderByAsc(SmsRepairCheckDetail::getDetailSort));
        RangeTypeEnum rangeTypeEnum;
        if (firstDetail.getProcessObjectType() == REPAIR_CHECK_OBJECT_TYPE_PERSON) {
            rangeTypeEnum = RangeTypeEnum.RANGE_TYPE_ENUM_PERSON;
        } else {
            rangeTypeEnum = RangeTypeEnum.RANGE_TYPE_ENUM_ROLE;
        }
        List<String> rangeList = new ArrayList<>();
        rangeList.add(firstDetail.getProcessObjectId());

        newTipsUtil.addNewTips(TipsTypeEnum.TIPS_TYPE_ENUM_ALLOW,
                user_id,
                rangeTypeEnum,
                rangeList,
                AppTypeEnum.APP_TYPE_ENUM_REPAIR_CHECK_APPLICATION,
                application_id,
                firstDetail.getId());
        return CommonResult.success();
    }

    @Transactional
    @Override
    public ResponseResult repairCheckCancel(SmsRepairCheckApplyCancelVO cancelVO, String user_id) {
        if (isNullOrEmpty(cancelVO.getApplyId())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        //查看审批表是否存在且是否为本人
        SmsRepairCheckApply paymentExamine =
                smsRepairCheckApplyMapper.selectOne(new QueryWrapper<SmsRepairCheckApply>()
                        .lambda()
                        .eq(SmsRepairCheckApply::getId, cancelVO.getApplyId())
                        .eq(SmsRepairCheckApply::getApplyUserId, user_id));
        if (paymentExamine == null || isNullOrEmpty(paymentExamine.getId())) {
            return CommonResult.failed(CommonCodeEnum.REPAIR_CHECK_NOT_EXIST);
        }
        if (paymentExamine.getAllowStatus() != REPAIR_CHECK_STATUS_WAIT_ALLOW) {
            return CommonResult.failed(CommonCodeEnum.REPAIR_CHECK_CANCEL_FAIL_ALLOWED);
        }
        //判断是否审批中
//        List<SmsRepairCheckDetail> detailList =
//                smsRepairCheckDetailMapper.selectList(new QueryWrapper<SmsRepairCheckDetail>()
//                        .lambda()
//                        .eq(SmsRepairCheckDetail::getApplicationId, cancelVO.getApplyId())
//                        .eq(SmsRepairCheckDetail::getDetailAllowStatus, REPAIR_CHECK_STATUS_PASS));
//        if (detailList != null && detailList.size() > 0) {
//            return CommonResult.failed(CommonCodeEnum.REPAIR_CHECK_CANCEL_FAIL_ALLOWING);
//        }

        //撤回审批
        SmsRepairCheckApply cancelExamine = new SmsRepairCheckApply();
        cancelExamine.setId(cancelVO.getApplyId());
        cancelExamine.setAllowStatus(REPAIR_CHECK_STATUS_CANCEL);
        cancelExamine.setEndTime(new Date());
        smsRepairCheckApplyMapper.updateById(cancelExamine);

        //修改节点状态
        SmsRepairCheckDetail cancelExamineDetail = new SmsRepairCheckDetail();
        cancelExamineDetail.setDetailAllowStatus(REPAIR_CHECK_STATUS_CANCEL);

        smsRepairCheckDetailMapper.update(cancelExamineDetail, new QueryWrapper<SmsRepairCheckDetail>()
                .lambda()
                .eq(SmsRepairCheckDetail::getApplicationId, cancelVO.getApplyId())
                .eq(SmsRepairCheckDetail::getDetailAllowStatus, REPAIR_CHECK_STATUS_WAIT_ALLOW));

        //消息通知
        newTipsUtil.cancelFinishTips(cancelVO.getApplyId());
        return CommonResult.success();
    }

    @Transactional
    @Override
    public ResponseResult allowRepairCheck(SmsRepairCheckApplyAllowVO allowVO, String user_id) {
        if (isNullOrEmpty(allowVO.getApplyId())
//                || isNullOrEmpty(allowVO.getDetailAllowStatus()
        ) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        if (allowVO.getDetailAllowStatus() != REPAIR_CHECK_STATUS_PASS
                && allowVO.getDetailAllowStatus() != REPAIR_CHECK_STATUS_DENY) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        SmsRepairCheckDetail applicationDetail;
        applicationDetail =
                smsRepairCheckDetailMapper.selectOne(new QueryWrapper<SmsRepairCheckDetail>()
                        .lambda()
                        .eq(SmsRepairCheckDetail::getApplicationId, allowVO.getApplyId())
                        .eq(SmsRepairCheckDetail::getId, allowVO.getDetailId())
                        .eq(SmsRepairCheckDetail::getDetailAllowStatus, REPAIR_CHECK_STATUS_WAIT_ALLOW));
        if (isNullOrEmpty(applicationDetail)) {
            return CommonResult.failed(CommonCodeEnum.REPAIR_CHECK_ALLOW_FAIL);
        }
        //判断该节点是否本人审批（防止调节点审批）
        //历史数据问题
        if(isNullOrEmpty(applicationDetail.getProcessObjectType())){
            applicationDetail = smsRepairCheckDetailMapper.selectOne(new QueryWrapper<SmsRepairCheckDetail>()
                    .lambda()
                    .eq(SmsRepairCheckDetail::getApplicationId, allowVO.getApplyId())
                    .eq(SmsRepairCheckDetail::getDetailSort, applicationDetail.getDetailSort() + 1));
        }
        if (applicationDetail.getProcessObjectType() == REPAIR_CHECK_OBJECT_TYPE_PERSON) {
            if (!applicationDetail.getProcessObjectId().equals(user_id)) {
                return CommonResult.failed(CommonCodeEnum.REPAIR_CHECK_ALLOW_FAIL);
            }
        } else {
            List<String> roleList = cacheUtil.getRoleList(user_id);
            SmsRepairCheckDetail finalApplicationDetail = applicationDetail;
            List<String> filterRoleList = roleList.stream().filter(role -> role.equals(finalApplicationDetail.getProcessObjectId())).collect(Collectors.toList());
            if (filterRoleList.size() < 1) {
                return CommonResult.failed(CommonCodeEnum.REPAIR_CHECK_ALLOW_FAIL);
            }
        }
        if (!applicationDetail.getDetailSort().equals(1)) {
            SmsRepairCheckDetail preDetail =
                    smsRepairCheckDetailMapper.selectOne(new QueryWrapper<SmsRepairCheckDetail>()
                            .lambda()
                            .eq(SmsRepairCheckDetail::getApplicationId, allowVO.getApplyId())
                            .eq(SmsRepairCheckDetail::getDetailSort, applicationDetail.getDetailSort() - 1));
            if (preDetail != null && !isNullOrEmpty(preDetail.getId())) {
                if (preDetail.getDetailAllowStatus() != REPAIR_CHECK_STATUS_PASS) {
                    return CommonResult.failed(CommonCodeEnum.REPAIR_CHECK_ALLOW_FAIL);
                }
            }
        }

        //判断是否后勤处，后勤处指定检修人
        if (applicationDetail.getProcessName().equals(PROCESS_NAME_LOGISTICS) && allowVO.getDetailAllowStatus() == REPAIR_CHECK_STATUS_PASS) {
            //校验检修人是否传了
            if (isNullOrEmpty(allowVO.getProcessCheckId())) {
                ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.REPAIR_CHECK_NOT_FIND));
            }
            SmsRepairCheckApply apply = new SmsRepairCheckApply();
            apply.setId(allowVO.getApplyId());
            apply.setApplyBadReason(allowVO.getApplyBadReason());
            smsRepairCheckApplyMapper.updateById(apply);
            //检修人节点修改
            SmsRepairCheckDetail detail = new SmsRepairCheckDetail();
            detail.setProcessObjectId(allowVO.getProcessCheckId());
            detail.setProcessObjectType(REPAIR_CHECK_OBJECT_TYPE_PERSON);
            smsRepairCheckDetailMapper.update(detail,new LambdaQueryWrapper<SmsRepairCheckDetail>()
            .eq(SmsRepairCheckDetail::getApplicationId,allowVO.getApplyId())
            .eq(SmsRepairCheckDetail::getProcessName,PROCESS_NAME_MAINTENANCE));

        }
        if (applicationDetail.getProcessName().equals(PROCESS_NAME_MAINTENANCE) && allowVO.getDetailAllowStatus() == REPAIR_CHECK_STATUS_PASS) {
            SmsRepairCheckApply apply = new SmsRepairCheckApply();
            apply.setId(allowVO.getApplyId());
            apply.setApplyFixedTime(new Date());
//            apply.setApplyBadReason(allowVO.getApplyBadReason());
            apply.setApplyFixedResult(allowVO.getApplyFixedResult());
            apply.setApplyFixedPhone(allowVO.getApplyFixedPhone());
            apply.setApplyHandleOption(allowVO.getApplyHandleOption());
            apply.setApplyCompensationAmount(allowVO.getApplyCompensationAmount());
            smsRepairCheckApplyMapper.updateById(apply);
//            //免赔时删除检修人确认节点
//            if(allowVO.getApplyHandleOption() == REPAIR_CHECK_OPTION_MP){
//                smsRepairCheckDetailMapper.delete(new LambdaQueryWrapper<SmsRepairCheckDetail>()
//                .eq(SmsRepairCheckDetail::getApplicationId,allowVO.getApplyId())
//                .eq(SmsRepairCheckDetail::getProcessName,PROCESS_NAME_MAINTENANCE_CONFIRMATION));
//                SmsRepairCheckDetail smsRepairCheckDetail = new SmsRepairCheckDetail();
//                smsRepairCheckDetail.setDetailSort(4);
//                smsRepairCheckDetailMapper.update(smsRepairCheckDetail,new LambdaQueryWrapper<SmsRepairCheckDetail>()
//                .eq(SmsRepairCheckDetail::getApplicationId,allowVO.getApplyId())
//                .eq(SmsRepairCheckDetail::getDetailSort,5));
//            }


        }
        QueryWrapper<SmsRepairCheckApply> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.lambda().eq(SmsRepairCheckApply::getId, allowVO.getApplyId());
        SmsRepairCheckApply apply2 = smsRepairCheckApplyMapper.selectOne(queryWrapper2);
//        if (applicationDetail.getProcessName().equals(PROCESS_NAME_FINANCE) && apply2.getApplyHandleOption() == REPAIR_CHECK_OPTION_MP) {
//            SmsRepairCheckDetail detail = new SmsRepairCheckDetail();
//            QueryWrapper<SmsRepairCheckApply> queryWrapper1 = new QueryWrapper<>();
//            queryWrapper1.lambda().eq(SmsRepairCheckApply::getId, allowVO.getApplyId());
//            SmsRepairCheckApply apply1 = smsRepairCheckApplyMapper.selectOne(queryWrapper1);
//            detail.setProcessObjectId(apply1.getApplyUserId());
//            detail.setProcessObjectType(REPAIR_CHECK_OBJECT_TYPE_PERSON);
//            smsRepairCheckDetailMapper.update(detail,new LambdaQueryWrapper<SmsRepairCheckDetail>()
//            .eq(SmsRepairCheckDetail::getApplicationId,allowVO.getApplyId())
//            .eq(SmsRepairCheckDetail::getProcessName,PROCESS_NAME_REPAIR));
//        }
//        QueryWrapper<SmsRepairCheckApply> queryWrapper = new QueryWrapper<>();
//        queryWrapper.lambda().eq(SmsRepairCheckApply::getId, allowVO.getApplyId());
//        SmsRepairCheckApply apply = smsRepairCheckApplyMapper.selectOne(queryWrapper);
//        if (applicationDetail.getProcessName().equals(PROCESS_NAME_FINANCE) && apply.getApplyHandleOption() != REPAIR_CHECK_OPTION_MP) {
//            QueryWrapper<SmsRepairCheckDetail> queryWrapper4 = new QueryWrapper<>();
//            queryWrapper4.lambda().eq(SmsRepairCheckDetail::getProcessName, PROCESS_NAME_MAINTENANCE)
//                    .eq(SmsRepairCheckDetail::getApplicationId, allowVO.getApplyId());
//            SmsRepairCheckDetail detail = smsRepairCheckDetailMapper.selectOne(queryWrapper4);
//            if (!isNullOrEmpty(detail)) {
//                SmsRepairCheckDetail detail1 = new SmsRepairCheckDetail();
//                detail1.setProcessObjectId(detail.getProcessObjectId());
//                detail1.setProcessObjectType(REPAIR_CHECK_OBJECT_TYPE_PERSON);
//                smsRepairCheckDetailMapper.update(detail1,new LambdaQueryWrapper<SmsRepairCheckDetail>()
//                .eq(SmsRepairCheckDetail::getApplicationId,allowVO.getApplyId())
//                .eq(SmsRepairCheckDetail::getProcessName,PROCESS_NAME_MAINTENANCE_CONFIRMATION));
//
//            }
//
//        }


        if (applicationDetail.getProcessName().equals(PROCESS_NAME_MAINTENANCE_CONFIRMATION)) {
            SmsRepairCheckDetail detail = new SmsRepairCheckDetail();
//            detail.setApplicationId(allowVO.getApplyId());
            QueryWrapper<SmsRepairCheckApply> queryWrapper3 = new QueryWrapper<>();
            queryWrapper3.lambda().eq(SmsRepairCheckApply::getId, allowVO.getApplyId());
            SmsRepairCheckApply apply1 = smsRepairCheckApplyMapper.selectOne(queryWrapper3);
            detail.setProcessObjectId(apply1.getApplyUserId());
//            detail.setProcessName("报修人");
            detail.setProcessObjectType(REPAIR_CHECK_OBJECT_TYPE_PERSON);
//            detail.setDetailSort(applicationDetail.getDetailSort() + 1);
            smsRepairCheckDetailMapper.update(detail,new LambdaQueryWrapper<SmsRepairCheckDetail>()
            .eq(SmsRepairCheckDetail::getApplicationId,allowVO.getApplyId())
            .eq(SmsRepairCheckDetail::getProcessName,PROCESS_NAME_REPAIR));
        }
        SmsRepairCheckDetail allowDetail = new SmsRepairCheckDetail();
        allowDetail.setId(allowVO.getDetailId());
        allowDetail.setDetailAllowStatus(allowVO.getDetailAllowStatus());
        if (!isNullOrEmpty(allowVO.getDetailAllowOpinion())) {
            allowDetail.setDetailAllowOption(allowVO.getDetailAllowOpinion());
        }
        Date nowDate = new Date();
        allowDetail.setDetailAllowTime(nowDate);
        allowDetail.setDetailAllowUserId(user_id);

        if (applicationDetail.getProcessIsSign()) {
            if (isNullOrEmpty(allowVO.getDetailAllowSign())) {
                ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.INVALID_PARAM));
            }
            allowDetail.setDetailAllowSign(allowVO.getDetailAllowSign());
        }
        if (applicationDetail.getProcessIsStamp()) {
            if (isNullOrEmpty(allowVO.getDetailAllowStamp())) {
                ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.INVALID_PARAM));
            }
            allowDetail.setDetailAllowStamp(allowVO.getDetailAllowStamp());
        }
        smsRepairCheckDetailMapper.updateById(allowDetail);

        boolean is_done = false;

        //判断是否最后一个节点 是否驳回

        Integer detailCount = smsRepairCheckDetailMapper.selectCount(new QueryWrapper<SmsRepairCheckDetail>()
                .lambda()
                .eq(SmsRepairCheckDetail::getApplicationId, allowVO.getApplyId()));
//        if(applicationDetail.getProcessName().equals(PROCESS_NAME_FINANCE) && !isNullOrEmpty(apply.getApplyHandleOption()) && apply.getApplyHandleOption() == REPAIR_CHECK_OPTION_MP){
//            detailCount++;
//        }
        if (detailCount.equals(applicationDetail.getDetailSort()) || allowVO.getDetailAllowStatus() == REPAIR_CHECK_STATUS_DENY) {
            is_done = true;

            SmsRepairCheckApply updateApplication = new SmsRepairCheckApply();
            updateApplication.setId(allowVO.getApplyId());
            updateApplication.setEndTime(nowDate);
            updateApplication.setAllowStatus(allowVO.getDetailAllowStatus());
            smsRepairCheckApplyMapper.updateById(updateApplication);
        }

        //节点驳回 重置其余节点状态
        if (allowVO.getDetailAllowStatus() == REPAIR_CHECK_STATUS_DENY) {
            SmsRepairCheckDetail updateDenyDetail =
                    new SmsRepairCheckDetail();
            updateDenyDetail.setDetailAllowStatus(REPAIR_CHECK_STATUS_DENY_FINISH);
            smsRepairCheckDetailMapper.update(updateDenyDetail, new QueryWrapper<SmsRepairCheckDetail>()
                    .lambda()
                    .eq(SmsRepairCheckDetail::getApplicationId, allowVO.getApplyId())
                    .eq(SmsRepairCheckDetail::getDetailAllowStatus, REPAIR_CHECK_STATUS_WAIT_ALLOW));
        }


        //消息通知
        if (is_done) {
            boolean result_status = false;
            if (allowVO.getDetailAllowStatus() == REPAIR_CHECK_STATUS_PASS) {
                result_status = true;
            }
            newTipsUtil.allowFinishTips(allowVO.getApplyId(), user_id, result_status);
        } else {
            int i = applicationDetail.getDetailSort();

//            if(applicationDetail.getProcessName().equals(PROCESS_NAME_FINANCE) && !isNullOrEmpty(apply.getApplyHandleOption()) && apply.getApplyHandleOption() == REPAIR_CHECK_OPTION_MP){
//                i++;
//            }
            SmsRepairCheckDetail nextDetail =
                    smsRepairCheckDetailMapper.selectOne(new QueryWrapper<SmsRepairCheckDetail>()
                            .lambda()
                            .eq(SmsRepairCheckDetail::getApplicationId, allowVO.getApplyId())
                            .eq(SmsRepairCheckDetail::getDetailSort, i + 1));
            RangeTypeEnum rangeTypeEnum;
            if (nextDetail.getProcessIsApplicationEdit().equals(1)) {
                rangeTypeEnum = RangeTypeEnum.RANGE_TYPE_ENUM_PERSON;
            } else {
                if (nextDetail.getProcessObjectType() == REPAIR_CHECK_OBJECT_TYPE_ROLE) {
                    rangeTypeEnum = RangeTypeEnum.RANGE_TYPE_ENUM_ROLE;
                } else {
                    rangeTypeEnum = RangeTypeEnum.RANGE_TYPE_ENUM_PERSON;
                }
            }

            List<String> rangeIDList = new ArrayList<>();
            rangeIDList.add(nextDetail.getProcessObjectId());
            newTipsUtil.allowContinueTips(allowVO.getApplyId(),
                    user_id,
                    rangeTypeEnum,
                    rangeIDList,
                    nextDetail.getId());
        }
        return CommonResult.success();
    }

    @Override
    public ResponseResult getRepairCheckList(Integer pageSize, String search_str, Integer pageNum, Integer apply_type, String user_id) {
        if (isNullOrEmpty(apply_type)) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        List<SmsRepairCheckApplyDTO> respList = new ArrayList<>();
        int total = 0;
        if (apply_type == REPAIR_CHECK_TYPE_APPLY) {
            Page<SmsRepairCheckApply> page = new Page<>(pageNum, pageSize);
            QueryWrapper<SmsRepairCheckApply> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda()
                    .eq(SmsRepairCheckApply::getApplyUserId, user_id)
                    .orderByDesc(SmsRepairCheckApply::getCreateTime);
            if (!isNullOrEmpty(search_str)) {
                queryWrapper.lambda().like(SmsRepairCheckApply::getApplyPerson, search_str);
            }
            smsRepairCheckApplyMapper.selectPage(page, queryWrapper);
            respList = page.getRecords()
                    .stream()
                    .map(smsExamine -> {
                        SmsRepairCheckApplyDTO smsPaymentExamineResp =
                                new SmsRepairCheckApplyDTO();
                        BeanUtils.copyProperties(smsExamine, smsPaymentExamineResp);
                        smsPaymentExamineResp.setApplyId(smsExamine.getId());

                        SmsUser smsUser = cacheUtil.getUserInfo(smsExamine.getApplyUserId());
                        SmsRepairCheckUserDTO smsExamineUserResp = new SmsRepairCheckUserDTO();
                        if (smsUser != null) {
                            BeanUtils.copyProperties(smsUser, smsExamineUserResp);
                        }
                        smsPaymentExamineResp.setApplyUserInfo(smsExamineUserResp);


                        return smsPaymentExamineResp;
                    })
                    .collect(Collectors.toList());
            total = (int) page.getTotal();
        } else if (apply_type == REPAIR_CHECK_TYPE_ALLOWED) {

            Page<SmsRepairCheckMPJDTO> page = new Page<>(pageNum, pageSize);
            MPJLambdaWrapper<SmsRepairCheckDetail> mpjLambdaWrapper = new MPJLambdaWrapper<>();
            mpjLambdaWrapper.selectAll(SmsRepairCheckDetail.class)
                    .selectAll(SmsRepairCheckApply.class)
                    .selectAs(SmsRepairCheckApply::getCreateTime, "createTime")
                    .selectAs(SmsRepairCheckDetail::getId, "detailId")
                    .leftJoin(SmsRepairCheckApply.class, SmsRepairCheckApply::getId, SmsRepairCheckDetail::getApplicationId)
                    .eq(SmsRepairCheckDetail::getDetailAllowUserId, user_id)
                    //.orderByDesc(SmsRepairCheckApply::getCreateTime)
                    .orderByDesc(SmsRepairCheckDetail::getDetailAllowTime)
            ;
            mpjLambdaWrapper.and(wrapper -> {
                wrapper.eq(SmsRepairCheckDetail::getDetailAllowStatus, REPAIR_CHECK_STATUS_PASS)
                        .or()
                        .eq(SmsRepairCheckDetail::getDetailAllowStatus, REPAIR_CHECK_STATUS_DENY);
            });
            if (!isNullOrEmpty(search_str)) {
                List<String> userIds = smsUserMapper.selectList(new QueryWrapper<SmsUser>()
                                .lambda()
                                .like(SmsUser::getRealName, search_str))
                        .stream()
                        .map(SmsUser::getId).collect(Collectors.toList());

                mpjLambdaWrapper.and(q -> {
                    q.like(SmsRepairCheckApply::getApplyPerson, search_str)
                            .or()
                            .like(SmsRepairCheckApply::getApplyRepairProject, search_str);
                    if (userIds.size() > 0) {
                        q.or().in(SmsCarUseReturnApplication::getReturnApplyUserId, userIds);
                    }
                });
            }
            smsRepairCheckMpjMapper.selectJoinPage(page, SmsRepairCheckMPJDTO.class, mpjLambdaWrapper);

            respList = page.getRecords()
                    .stream()
                    .map(smsApplicationMPJDTO -> {
                        SmsRepairCheckApplyDTO smsApplicationDTO = new SmsRepairCheckApplyDTO();
                        BeanUtils.copyProperties(smsApplicationMPJDTO, smsApplicationDTO);
                        smsApplicationDTO.setCreateTime(smsApplicationMPJDTO.getCreateTime());
                        smsApplicationDTO.setApplyId(smsApplicationMPJDTO.getApplicationId());
                        SmsUser applyUser = cacheUtil.getUserInfo(smsApplicationDTO.getApplyUserId());
                        SmsRepairCheckUserDTO userDTO = new SmsRepairCheckUserDTO();
                        if (applyUser != null) {
                            BeanUtils.copyProperties(applyUser, userDTO);
                        }
                        smsApplicationDTO.setApplyUserInfo(userDTO);

                        SmsUser allowUser = cacheUtil.getUserInfo(smsApplicationDTO.getDetailAllowUserId());
                        SmsRepairCheckUserDTO staffUserDTO = new SmsRepairCheckUserDTO();
                        if (allowUser != null) {
                            BeanUtils.copyProperties(allowUser, staffUserDTO);
                        }
                        smsApplicationDTO.setAllowUserInfo(staffUserDTO);

                        return smsApplicationDTO;
                    })
                    .collect(Collectors.toList());
            total = (int) page.getTotal();

        } else if (apply_type == REPAIR_CHECK_TYPE_ALLOW_WAIT_ME) {
            List<String> roleList = cacheUtil.getRoleList(user_id);


            //获取所有待审批申请流程节点
            List<SmsRepairCheckDetail> detailList
                    = smsRepairCheckDetailMapper.selectList(new QueryWrapper<SmsRepairCheckDetail>()
                    .lambda()
                    .eq(SmsRepairCheckDetail::getDetailAllowStatus, REPAIR_CHECK_STATUS_WAIT_ALLOW)
            );

            List<SmsRepairCheckDetail> filterDetailList = detailList.stream()
                    .filter(detail -> {
                        if (detail.getProcessIsApplicationEdit().equals(1)) {
                            if (!detail.getProcessObjectId().equals(user_id)) {
                                return false;
                            }
                        } else {
                            if (!isNullOrEmpty(detail.getProcessObjectType()) && detail.getProcessObjectType() == REPAIR_CHECK_OBJECT_TYPE_PERSON) {
                                if (!detail.getProcessObjectId().equals(user_id)) {
                                    return false;
                                }
                            } else {
                                if (!isNullOrEmpty(detail.getProcessObjectId())) {
                                    List<String> filterRoleList = roleList.stream().filter(role -> role.equals(detail.getProcessObjectId())).collect(Collectors.toList());
                                    if (filterRoleList.size() < 1) {
                                        return false;
                                    }
                                }
                            }

                        }

                        if (detail.getDetailSort().equals(1)) {
                            return true;
                        }
                        //判断上一个流程节点是否完成
//                        int i = detail.getDetailSort();
//                        SmsRepairCheckApply apply = smsRepairCheckApplyMapper.selectOne(new LambdaQueryWrapper<SmsRepairCheckApply>()
//                                .eq(SmsRepairCheckApply::getId, detail.getApplicationId()));
//                        if(detail.getProcessName().equals(PROCESS_NAME_REPAIR) && !isNullOrEmpty(apply.getApplyHandleOption()) && apply.getApplyHandleOption() == REPAIR_CHECK_OPTION_MP){
//                            i--;
//                        }
                        SmsRepairCheckDetail preDetail =
                                smsRepairCheckDetailMapper.selectOne(new QueryWrapper<SmsRepairCheckDetail>()
                                        .lambda()
                                        .eq(SmsRepairCheckDetail::getApplicationId, detail.getApplicationId())
                                        .eq(SmsRepairCheckDetail::getDetailSort, detail.getDetailSort() - 1)
                                        .eq(SmsRepairCheckDetail::getDetailAllowStatus, REPAIR_CHECK_STATUS_PASS));
                        if (preDetail == null || isNullOrEmpty(preDetail.getId())) {
                            return false;
                        }
                        return true;
                    })
                    .collect(Collectors.toList());
            if (filterDetailList.size() > 0) {
                List<String> detailIDList = filterDetailList.stream().map(SmsRepairCheckDetail::getId).collect(Collectors.toList());

                Page<SmsRepairCheckDetail> page = new Page<>(pageNum, pageSize);
                QueryWrapper<SmsRepairCheckDetail> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda()
                        .in(SmsRepairCheckDetail::getId, detailIDList)
                        .orderByDesc(SmsRepairCheckDetail::getCreateTime);
                smsRepairCheckDetailMapper.selectPage(page, queryWrapper);

                respList = page.getRecords()
                        .stream()
                        .map(smsApplicationDetail -> {
                            SmsRepairCheckApply application
                                    = smsRepairCheckApplyMapper.selectById(smsApplicationDetail.getApplicationId());
                            SmsRepairCheckApplyDTO applicationDTO
                                    = new SmsRepairCheckApplyDTO();
                            BeanUtils.copyProperties(application, applicationDTO);
                            applicationDTO.setApplyId(smsApplicationDetail.getApplicationId());

                            SmsUser applyUser = cacheUtil.getUserInfo(applicationDTO.getApplyUserId());
                            SmsRepairCheckUserDTO applicationUserDTO = new SmsRepairCheckUserDTO();
                            if (applyUser != null) {
                                BeanUtils.copyProperties(applyUser, applicationUserDTO);
                            }
                            applicationDTO.setApplyUserInfo(applicationUserDTO);

                            applicationDTO.setDetailId(smsApplicationDetail.getId());

                            return applicationDTO;

                        })
                        .filter(q -> {
                            if (!isNullOrEmpty(search_str)) {
                                List<String> userIds = smsUserMapper.selectList(new QueryWrapper<SmsUser>()
                                                .lambda()
                                                .like(SmsUser::getRealName, search_str))
                                        .stream()
                                        .map(SmsUser::getId).collect(Collectors.toList());
                                if (q.getApplyRepairProject().contains(search_str) || q.getApplyPerson().contains(search_str)) {
                                    return true;
                                }
                                if (userIds.size() > 0 && userIds.contains(q.getApplyUserId())) {
                                    return true;
                                }
//                                QueryWrapper<SmsRepairCheckApply> queryWrapper1 = new QueryWrapper<>();
//                                queryWrapper1.lambda().eq(SmsRepairCheckApply::getId,q.getApplyId());
//                                queryWrapper1.lambda().and(w ->{
//                                    w.like(SmsRepairCheckApply::getApplyRepairProject,search_str)
//                                            .or()
//                                            .like(SmsRepairCheckApply::getApplyPerson,search_str);
//                                    if(userIds.size() > 0) {
//                                        w.or().in(SmsRepairCheckApply::getApplyUserId, userIds);
//                                    }
                                return false;
                            }
                            return true;

                        })
                        .collect(Collectors.toList());

            }
        }
        return CommonResult.success(respList, respList.size());
    }

    @Override
    public ResponseResult getRepairCheckDetail(String apply_id, String user_id) {
        if (isNullOrEmpty(apply_id)) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        SmsRepairCheckApply paymentExamine = smsRepairCheckApplyMapper.selectById(apply_id);
        if (paymentExamine == null || isNullOrEmpty(paymentExamine.getId())) {
            return CommonResult.failed(CommonCodeEnum.REPAIR_CHECK_NOT_EXIST);
        }

        SmsRepairCheckApplyDTO paymentExamineResp = new SmsRepairCheckApplyDTO();
        BeanUtils.copyProperties(paymentExamine, paymentExamineResp);
        paymentExamineResp.setApplyId(paymentExamine.getId());

        SmsUser smsUser = cacheUtil.getUserInfo(paymentExamineResp.getApplyUserId());
        SmsRepairCheckUserDTO smsExamineUserResp = new SmsRepairCheckUserDTO();
        if (smsUser != null) {
            BeanUtils.copyProperties(smsUser, smsExamineUserResp);
        }
        paymentExamineResp.setApplyUserInfo(smsExamineUserResp);

        List<SmsRepairCheckDetailDTO> detailRespList =
                smsRepairCheckDetailMapper.selectList(new QueryWrapper<SmsRepairCheckDetail>()
                                .lambda()
                                .eq(SmsRepairCheckDetail::getApplicationId, apply_id)
                                .orderByAsc(SmsRepairCheckDetail::getDetailSort))
                        .stream()
                        .map(detail -> {
                            SmsRepairCheckDetailDTO detailResp = new SmsRepairCheckDetailDTO();
                            BeanUtils.copyProperties(detail, detailResp);
                            detailResp.setDetailAllowOpinion(detail.getDetailAllowOption());

                            if(!isNullOrEmpty(detailResp.getProcessObjectType())) {
                                if (detailResp.getProcessObjectType() == REPAIR_CHECK_OBJECT_TYPE_PERSON) {
                                    SmsUser smsUser1 = smsUserMapper.selectById(detailResp.getProcessObjectId());
                                    if(!isNullOrEmpty(smsUser1)) {
                                        detailResp.setRealName(smsUser1.getRealName());
                                        detailResp.setHeadPic(smsUser1.getUserPic());
                                    }
                                } else if (detailResp.getProcessObjectType() == REPAIR_CHECK_OBJECT_TYPE_ROLE) {
                                    SmsRole smsRole = smsRoleMapper.selectById(detailResp.getProcessObjectId());
                                    if(!isNullOrEmpty(smsRole)) {
                                        detailResp.setRealName(smsRole.getRoleName());
                                    }
                                    //封装角色内用户
                                    List<SmsRepairCheckUserDTO> list = getRoleUserList(detailResp.getProcessObjectId());
                                    detailResp.setRoleUserList(list);
                                }
                            }
                            if (!isNullOrEmpty(detailResp.getDetailAllowUserId())) {
                                SmsUser userInfo = cacheUtil.getUserInfo(detailResp.getDetailAllowUserId());
                                SmsRepairCheckUserDTO paymentExamineUserResp = new SmsRepairCheckUserDTO();
                                if (userInfo != null) {
                                    BeanUtils.copyProperties(userInfo, paymentExamineUserResp);
                                }
                                detailResp.setAllowUserInfo(paymentExamineUserResp);
//                                QueryWrapper<SmsRepairCheckDetail> queryWrapper = new QueryWrapper<>();
//                                queryWrapper.lambda().eq(SmsRepairCheckDetail::getApplicationId, apply_id)
//                                        .eq(SmsRepairCheckDetail::getProcessName, "检修人");
//                                SmsRepairCheckDetail smsRepairCheckDetail = smsRepairCheckDetailMapper.selectOne(queryWrapper);
//                                if (!isNullOrEmpty(smsRepairCheckDetail)) {
//                                    QueryWrapper<SmsUser> queryWrapper1 = new QueryWrapper<>();
//                                    queryWrapper1.lambda().eq(SmsUser::getId, smsRepairCheckDetail.getProcessObjectId());
//                                    SmsUser smsUser1 = smsUserMapper.selectOne(queryWrapper1);
//                                    if (!isNullOrEmpty(smsUser1)) {
//                                        paymentExamineResp.setApplyFixedPerson(smsUser1.getRealName());
//                                    }
//                                }
                            }
                            return detailResp;
                        })
                        .collect(Collectors.toList());
        paymentExamineResp.setDetailList(detailRespList);

        return CommonResult.success(paymentExamineResp);
    }

    private List<SmsRepairCheckUserDTO> getRoleUserList(String role_id) {
        List<SmsRepairCheckUserDTO> list = new ArrayList<>();
        List<String> userIDList = smsUserRoleRelationMapper.selectList(new QueryWrapper<SmsUserRoleRelation>()
                        .lambda()
                        .eq(SmsUserRoleRelation::getRoleId, role_id))
                .stream()
                .map(SmsUserRoleRelation::getUserId)
                .collect(Collectors.toList());
        if (userIDList.size() > 0) {
            for (String user_id : userIDList) {
                SmsUser smsUser = cacheUtil.getUserInfo(user_id);
                if (smsUser == null) {
                    continue;
                }
                SmsRepairCheckUserDTO smsRepairCheckUserDTO = new SmsRepairCheckUserDTO();
                BeanUtils.copyProperties(smsUser, smsRepairCheckUserDTO);
                list.add(smsRepairCheckUserDTO);
            }
        }
        return list;
    }


    @Override
    public ResponseResult getRepairCheckOriginSettingProcess() {
        List<SmsRepairCheckOriginSettingProcessDTO> respList =
                smsRepairCheckProcessMapper.selectList(new QueryWrapper<SmsRepairCheckProcess>()
                                .lambda()
                                .eq(SmsRepairCheckProcess::getProcessIsApplicationEdit, true)
                                .eq(SmsRepairCheckProcess::getProcessIsUse, true)
                                .orderByAsc(SmsRepairCheckProcess::getProcessSort))
                        .stream()
                        .filter(process -> {
                            if (process.getProcessName().equals(PROCESS_NAME_LOGISTICS) || process.getProcessName().equals(PROCESS_NAME_FINANCE)) {
                                return true;
                            }
                            return false;
                        })
                        .map(process -> {
                            SmsRepairCheckOriginSettingProcessDTO smsPaymentExamineOriginSettingProcessResp =
                                    new SmsRepairCheckOriginSettingProcessDTO();
                            BeanUtils.copyProperties(process, smsPaymentExamineOriginSettingProcessResp);
                            return smsPaymentExamineOriginSettingProcessResp;
                        })
                        .collect(Collectors.toList());
        return CommonResult.success(respList);
    }

    @Override
    public ResponseResult selectAllRepairCheck(String apply_unit, Integer pageSize, Integer pageNum, Integer status) {
        QueryWrapper<SmsRepairCheckApply> queryWrapper = new QueryWrapper<>();
        if (!isNullOrEmpty(apply_unit)) {
            queryWrapper.lambda().like(SmsRepairCheckApply::getApplyPerson, apply_unit);
        }

        if (!isNullOrEmpty(status)) {
            queryWrapper.lambda().eq(SmsRepairCheckApply::getAllowStatus,status);
        }
        queryWrapper.orderByDesc("create_time");
        Page<SmsRepairCheckApply> page = new Page<>(pageNum, pageSize);
        List<SmsRepairCheckApplyDTO> collect;

        Page<SmsRepairCheckApply> appApplicationPage = smsRepairCheckApplyMapper.selectPage(page, queryWrapper);
        List<SmsRepairCheckApply> records = appApplicationPage.getRecords();
        collect = records.stream().map(appApplication -> {
            SmsRepairCheckApplyDTO appApplicationResp = new SmsRepairCheckApplyDTO();
            BeanUtils.copyProperties(appApplication, appApplicationResp);
            SmsUser smsUser = cacheUtil.getUserInfo(appApplicationResp.getApplyUserId());
            if (smsUser != null) {
                SmsRepairCheckUserDTO user = new SmsRepairCheckUserDTO();
                BeanUtils.copyProperties(smsUser, user);
                appApplicationResp.setApplyUserInfo(user);
            }

            return appApplicationResp;
        }).collect(Collectors.toList());

        int total = (int) page.getTotal();
        return CommonResult.success(collect, total);
    }


    @Override
    @Async
    public Future<ResponseResult> tableDownload(String apply_id, HttpServletResponse response) {
        SmsRepairCheckApply checkApply = smsRepairCheckApplyMapper.selectById(apply_id);
        if (checkApply == null || checkApply.getId() == null) {
            return new AsyncResult<>(CommonResult.failed(CommonCodeEnum.REPAIR_CHECK_NOT_EXIST));
        }
//        if (checkApply.getAllowStatus() == WORK_STATUS_WAIT_ALLOW) {
//            return new AsyncResult<>(CommonResult.failed(CommonCodeEnum.WORK_APPLICATION_DOWNLOAD_FAIL));
//        }

        String OSName = System.getProperty("os.name");
        String filePath = OSName.toLowerCase().startsWith("win") ? fileSavePathConstant.getFILE_DOWNLOAD_PATH()
                : fileSavePathConstant.getFILE_DOWNLOAD_PATH_LINUX();

        String newFilePath = filePath + apply_id + ".docx";
        String pdfFilePath = filePath + apply_id + ".pdf";

        File pdfFile = new File(pdfFilePath);

        //     if (!pdfFile.exists()) {
        try {

            Map<String, Object> map = new HashMap<>();
            if (checkApply.getApplyFixedTime() != null) {
                String signTime = TimeUtil.DateHanZiSimpleFormat(checkApply.getApplyFixedTime());
                map.put("fixedTime", signTime);
            }


            List<String> picTagList = new ArrayList<>();


            map.put("applyYbbName", checkApply.getApplyYbbName());
            map.put("applyPerson", checkApply.getApplyPerson());
            String sign1Time = TimeUtil.DateHanZiSimpleFormat(checkApply.getCreateTime());
            map.put("applyPhone", checkApply.getApplyPhone());
            map.put("repairTime", sign1Time);
            map.put("repairProject", checkApply.getApplyRepairProject());
            map.put("repairAddress", checkApply.getApplyRepairAddress());
            map.put("badReason", checkApply.getApplyBadReason());


            QueryWrapper<SmsRepairCheckDetail> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(SmsRepairCheckDetail::getApplicationId, apply_id)
                    .eq(SmsRepairCheckDetail::getProcessName, "检修人");
            SmsRepairCheckDetail detail = smsRepairCheckDetailMapper.selectOne(queryWrapper);
//                if(detail.getDetailAllowStatus()==REPAIR_CHECK_STATUS_PASS){
//
//                }
            for (int i = 1; i < 4; i++) {


                map.put("type" + i + "", "□");
                map.put("option" + i + "", "□");
            }
            if (!isNullOrEmpty(detail)) {

                //检修结果
                for (int i = 1; i < 4; i++) {
                    if (!isNullOrEmpty(checkApply.getApplyFixedResult())) {
                        if (checkApply.getApplyFixedResult().equals(i)) {
                            map.put("type" + i + "", "√");
                        } else {
                            map.put("type" + i + "", "□");
                        }
                    }

                }
                //处理意见
                for (int i = 1; i < 4; i++) {
                    if (!isNullOrEmpty(checkApply.getApplyHandleOption())) {
                        if (checkApply.getApplyHandleOption().equals(i)) {
                            map.put("option" + i + "", "√");
                        } else {
                            map.put("option" + i + "", "□");
                        }
                    }

                }
                SmsUser smsUser = smsUserMapper.selectById(detail.getDetailAllowUserId());
                if (smsUser != null) {
                    map.put("pricePerson", smsUser.getRealName());
                }
            }

            QueryWrapper<SmsRepairCheckDetail> queryWrapper5 = new QueryWrapper<>();
            queryWrapper5.lambda().eq(SmsRepairCheckDetail::getApplicationId, apply_id)
                    .eq(SmsRepairCheckDetail::getProcessName, "检修人");
            SmsRepairCheckDetail detail5 = smsRepairCheckDetailMapper.selectOne(queryWrapper5);
            if (!isNullOrEmpty(detail5) && detail5.getDetailAllowStatus() == REPAIR_CHECK_STATUS_PASS) {
                SmsUser smsUser = smsUserMapper.selectById(detail5.getProcessObjectId());
                map.put("fixedPerson", smsUser.getRealName());
                map.put("fixedPhone", checkApply.getApplyFixedPhone());
                if (isNullOrEmpty(checkApply.getApplyCompensationAmount())) {
                    map.put("amount", "");
                }
                map.put("amount", checkApply.getApplyCompensationAmount() + "元");

            }
            map.put("applyNote", checkApply.getApplyNote());
            QueryWrapper<SmsRepairCheckDetail> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.lambda().eq(SmsRepairCheckDetail::getApplicationId, apply_id)
                    .eq(SmsRepairCheckDetail::getProcessName, "后勤处");
            SmsRepairCheckDetail detail1 = smsRepairCheckDetailMapper.selectOne(queryWrapper1);
            if (!isNullOrEmpty(detail1)) {
                if (!isNullOrEmpty(detail1.getDetailAllowSign())) {
                    String[] splitStr = detail1.getDetailAllowSign().split("=");
                    String fileName = splitStr[splitStr.length - 1];
                    File file = new File(filePath + fileName);
                    InputStream inputStream = new FileInputStream(file);
                    PictureRenderData pictures = Pictures.ofStream(inputStream,
                            PictureType.PNG).size(60, 30).create();
                    map.put("allowHqSign" + "", pictures);
                    picTagList.add("allowHqSign");
                } else {
                    map.put("allowHqSign", "");
                }
            }


            QueryWrapper<SmsRepairCheckDetail> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.lambda().eq(SmsRepairCheckDetail::getApplicationId, apply_id)
                    .eq(SmsRepairCheckDetail::getProcessName, "检修人");
            SmsRepairCheckDetail detail2 = smsRepairCheckDetailMapper.selectOne(queryWrapper2);
            if (!isNullOrEmpty(detail2)) {
                if (!isNullOrEmpty(detail2.getDetailAllowSign())) {
                    String[] splitStr1 = detail2.getDetailAllowSign().split("=");
                    String fileName1 = splitStr1[splitStr1.length - 1];
                    File file1 = new File(filePath + fileName1);
                    InputStream inputStream1 = new FileInputStream(file1);
                    PictureRenderData pictures1 = Pictures.ofStream(inputStream1,
                            PictureType.PNG).size(60, 30).create();
                    map.put("fixedSign" + "", pictures1);
                    picTagList.add("fixedSign");
                } else {
                    map.put("fixedSign", "");
                }
            }


            QueryWrapper<SmsRepairCheckDetail> queryWrapper3 = new QueryWrapper<>();
            queryWrapper3.lambda().eq(SmsRepairCheckDetail::getApplicationId, apply_id)
                    .eq(SmsRepairCheckDetail::getProcessName, "报修人");
            SmsRepairCheckDetail detail3 = smsRepairCheckDetailMapper.selectOne(queryWrapper3);
            if (!isNullOrEmpty(detail3)) {
                if (!isNullOrEmpty(detail3.getDetailAllowSign())) {
                    String[] splitStr3 = detail3.getDetailAllowSign().split("=");
                    String fileName3 = splitStr3[splitStr3.length - 1];
                    File file3 = new File(filePath + fileName3);
                    InputStream inputStream3 = new FileInputStream(file3);
                    PictureRenderData pictures3 = Pictures.ofStream(inputStream3,
                            PictureType.PNG).size(60, 30).create();
                    map.put("applySign" + "", pictures3);
                    picTagList.add("applySign");
                } else {
                    map.put("applySign", "");
                }
            }


            QueryWrapper<SmsRepairCheckDetail> queryWrapper4 = new QueryWrapper<>();
            queryWrapper4.lambda().eq(SmsRepairCheckDetail::getApplicationId, apply_id)
                    .eq(SmsRepairCheckDetail::getProcessName, "财务");
            SmsRepairCheckDetail detail4 = smsRepairCheckDetailMapper.selectOne(queryWrapper4);

            if (!isNullOrEmpty(detail4)) {
                if (!isNullOrEmpty(detail4.getDetailAllowSign())) {

                    String[] splitStr4 = detail4.getDetailAllowSign().split("=");
                    String fileName4 = splitStr4[splitStr4.length - 1];
                    File file4 = new File(filePath + fileName4);
                    if (file4.exists()) {
                        InputStream inputStream4 = new FileInputStream(file4);
                        PictureRenderData pictures4 = Pictures.ofStream(inputStream4,
                                PictureType.PNG).size(60, 30).create();
                        map.put("cwSign" + "", pictures4);
                        picTagList.add("cwSign");
                    }

                } else {
                    map.put("cwSign", "");
                }
            }


            ClassPathResource resource = new ClassPathResource("applyTemplates/repairCheckApply.docx");
            InputStream is = resource.getInputStream();
            FileOutputStream outputStream = new FileOutputStream(newFilePath);

            XWPFTemplate template = XWPFTemplate.compile(is);

            //配置图片标签
            Configure config = template.getConfig();
            for (String tag : picTagList
            ) {
                config.customPolicy(tag, new PictureRenderPolicy());
            }
            template.render(map);

            template.write(outputStream);

            is.close();
            outputStream.close();
            template.close();

            //word转pdf
            File destOri = new File(newFilePath);
            FileInputStream fileInputStream = new FileInputStream(destOri);
            FileOutputStream fileOutputStream = new FileOutputStream(pdfFilePath);

            Document document = new Document();
            document.loadFromStream(fileInputStream, FileFormat.Docx);
            //保存为PDF
            document.saveToFile(pdfFilePath, FileFormat.PDF);


            fileInputStream.close();
            fileOutputStream.close();
            document.close();

            log.debug("文件生成完成!");
        } catch (Exception e) {
            e.printStackTrace();
            return new AsyncResult<>(CommonResult.failed(CommonCodeEnum.FAIL));
        }
        //  }
        try {
            // 加载PDF文档
            PDDocument doc = PDDocument.load(pdfFile);
            doc.setAllSecurityToBeRemoved(true);
            // 创建水印
//            String watermark = "南充电影工业职业学院";
//            PDPageContentStream contentStream;
//
//            for (PDPage page : doc.getPages()) {
//                contentStream = new PDPageContentStream(doc, page, PDPageContentStream.AppendMode.APPEND, true, true);
//
//                //加载字体
//                ClassPathResource resource = new ClassPathResource("fonts/123.ttf");
//                InputStream is = resource.getInputStream();
//                PDFont font = PDType0Font.load(doc, is);
//
//
//                int startX = 0; // 起始位置 x 坐标
//                int startY = 0; // 起始位置 y 坐标
//                float angle = -45; // 角度
//                float interval = 220; // 间隔
//                float opacity = 0.3f; // 透明度
//                int colorR = 127; // 颜色 red 值
//                int colorG = 127; // 颜色 green 值
//                int colorB = 127; // 颜色 blue 值
//
//                //透明的
//                PDExtendedGraphicsState r0 = new PDExtendedGraphicsState();
//                r0.setNonStrokingAlphaConstant(opacity);
//                r0.setAlphaSourceFlag(true);
//                contentStream.setGraphicsStateParameters(r0);
//
//                //水印颜色
//                contentStream.setNonStrokingColor(colorR, colorG, colorB);
//                contentStream.beginText();
//                contentStream.setFont(font, 30f);
//
//                int x_times = (int) Math.ceil(page.getMediaBox().getWidth() / interval);
//                int y_times = (int) Math.ceil(page.getMediaBox().getHeight() / interval);
//                for (int x = startX; x <= x_times; x++) {
//                    for (int y = startY; y <= y_times; y++) {
//                        contentStream.setTextRotation(angle, (x * interval), (y * interval));
//                        contentStream.showText(watermark);
//                    }
//                }
//                contentStream.endText();
//                contentStream.restoreGraphicsState();
//                contentStream.close();
//                is.close();
//            }

//            response.reset();
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/vnd.pdf;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("维修报审单预览.pdf", "utf-8"));
            response.setHeader("Access-Control-Expose-Headers", "file-type,file-name");
            response.setHeader("file-name", URLEncoder.encode("维修报审单预览.pdf", "utf-8"));
            response.setHeader("file-type", "download");
            //刷新缓冲
            response.flushBuffer();

            // 保存PDF文档
            doc.save(response.getOutputStream());
            doc.close();
        } catch (Exception e) {
            e.printStackTrace();
            return new AsyncResult<>(CommonResult.failed(CommonCodeEnum.FAIL));

        }
        return null;
    }

    private String filterResultNull(String resultStr) {
        if (resultStr == null || resultStr.equals("null")) {
            return "";
        }
        return resultStr;
    }

    @Autowired
    private ApiModelUtil apiModelUtil;

    @Override
    @Async
    public Future<ResponseResult> exportRepairCheck(SmsRepairCheckExportVO smsRepairCheckExportVO, HttpServletResponse response) {
        if (isNullOrEmpty(smsRepairCheckExportVO.getIsExportProcess())) {
            return new AsyncResult<>(CommonResult.failed(CommonCodeEnum.INVALID_PARAM));
        }
        try {
            QueryWrapper<SmsRepairCheckApply> queryWrapper = new QueryWrapper<>();
//            if (!isNullOrEmpty(smsRepairCheckExportVO.getId())) {
//                queryWrapper.lambda().eq(SmsRepairCheckApply::getId, smsRepairCheckExportVO.getId());
//            }
            if (!isNullOrEmpty(smsRepairCheckExportVO.getApplyPerson())) {
                queryWrapper.lambda().like(SmsRepairCheckApply::getApplyPerson, smsRepairCheckExportVO.getApplyPerson());
            }
            if (!isNullOrEmpty(smsRepairCheckExportVO.getApplyPerson())) {
                List<String> userList = smsUserMapper.selectList(new QueryWrapper<SmsUser>()
                                .lambda()
                                .like(SmsUser::getRealName, smsRepairCheckExportVO.getApplyPerson()))
                        .stream()
                        .map(SmsUser::getId)
                        .collect(Collectors.toList());
                if (userList.size() > 0) {
                    queryWrapper.lambda().in(SmsRepairCheckApply::getApplyUserId, userList);
                }
            }
            queryWrapper.lambda().orderByDesc(SmsRepairCheckApply::getCreateTime);
            List<SmsRepairCheckApply> list = smsRepairCheckApplyMapper.selectList(queryWrapper);
            //表头数据
            String[] header = smsRepairCheckExportVO.getLimitColumn().toArray(new String[0]);
            double sheetNum;
            //声明一个工作簿
            HSSFWorkbook workbook = new HSSFWorkbook();
            if (list != null && list.size() > 0) {
                sheetNum = Math.ceil((double) list.size() / PER_SHEET_NUM);
                for (int k = 0; k < sheetNum; k++) {
                    //生成一个表格，设置表格名称为"资源导出表"
                    HSSFSheet sheet = workbook.createSheet("维修报审记录导出表" + (k + 1));

                    //设置表格列宽度为10个字节
                    sheet.setDefaultColumnWidth(15);
                    //创建标题的显示样式
                    HSSFCellStyle headerStyle = workbook.createCellStyle();
                    headerStyle.setFillForegroundColor(IndexedColors.YELLOW.index);
                    headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);

                    HSSFFont f = workbook.createFont();
                    f.setFontHeightInPoints((short) 10);//字号
                    f.setBold(true);//加粗
                    headerStyle.setFont(f);
                    //创建第一行表头
                    HSSFRow headrow = sheet.createRow(0);

                    //遍历添加表头(下面模拟遍历学生，也是同样的操作过程)
                    for (int i = 0; i < header.length + 1; i++) {
                        //创建一个单元格
                        HSSFCell cell = headrow.createCell(i);

                        if (i == 0) {
                            //创建一个内容对象
                            HSSFRichTextString text = new HSSFRichTextString("序号");
                            //将内容对象的文字内容写入到单元格中
                            cell.setCellValue(text);
                            cell.setCellStyle(headerStyle);
                            continue;
                        }
                        //创建一个内容对象
                        String header1 = apiModelUtil.getFieldValueByFieldName(SmsRepairCheckApply.class, header[i - 1]);
                        HSSFRichTextString text = new HSSFRichTextString(header1);

                        //将内容对象的文字内容写入到单元格中
                        cell.setCellValue(text);
                        cell.setCellStyle(headerStyle);
                    }

                    //判断是否需要添加流程表头
                    if (smsRepairCheckExportVO.getIsExportProcess() == EXPORT_PROCESS_TRUE) {
                        HSSFCell cell = headrow.createCell(header.length + 1);

                        HSSFRichTextString text = new HSSFRichTextString("审批流程");

                        //将内容对象的文字内容写入到单元格中
                        cell.setCellValue(text);
                        cell.setCellStyle(headerStyle);
                    }

                    int range = PER_SHEET_NUM;
                    if (k + 1 == sheetNum) {
                        range = list.size() - (PER_SHEET_NUM) * k;
                    }
                    for (int i = 0; i < range; i++) {
                        //创建一行
                        HSSFRow row1 = sheet.createRow(i + 1);
                        SmsRepairCheckApply checkApply = list.get((PER_SHEET_NUM) * k + i);
                        Map map = JSONObject.parseObject(JSON.toJSONString(checkApply), Map.class);
                        row1.createCell(0).setCellValue(new HSSFRichTextString(i + 1 + ""));
                        for (int j = 0; j < header.length; j++) {
                            String rowContent = "";
                            if (map.get(header[j]) instanceof Long) {
                                rowContent = TimeUtil.DateHanZiSimpleTimestamp((long) map.get(header[j]));
                            } else {
                                if (header[j].equals("applyUserId")) {
                                    SmsUser smsUser = cacheUtil.getUserInfo(checkApply.getApplyUserId());
                                    if (smsUser != null) {
                                        rowContent = smsUser.getRealName();
                                    } else {
                                        rowContent = "";
                                    }
                                } else {
                                    rowContent = (String) map.get(header[j]);
                                }
                            }
                            row1.createCell(j + 1).setCellValue(new HSSFRichTextString(rowContent));
                        }

                        if (smsRepairCheckExportVO.getIsExportProcess() == EXPORT_PROCESS_TRUE) {
                            List<SmsRepairCheckDetail> detailList = smsRepairCheckDetailMapper.selectList(new QueryWrapper<SmsRepairCheckDetail>()
                                    .lambda()
                                    .eq(SmsRepairCheckDetail::getApplicationId, checkApply.getId()));
                            StringBuilder stringBuilder = new StringBuilder();
                            if (detailList != null && detailList.size() > 0) {
                                int sort = 1;
                                for (SmsRepairCheckDetail detail : detailList) {
                                    if (detail.getDetailAllowStatus() != EXAMINE_STATUS_PASS && detail.getDetailAllowStatus() != EXAMINE_STATUS_DENY) {
                                        sort += 1;
                                        break;
                                    }
                                    stringBuilder.append(detail.getProcessName()).append(":\n");

                                    SmsUser smsUser = smsUserMapper.selectById(detail.getProcessObjectId());
                                    if (smsUser == null) {
                                        stringBuilder.append("审批人：").append("\n");
                                    } else {
                                        stringBuilder.append("审批人：").append(smsUser.getRealName()).append("\n");
                                    }

                                    if (detail.getDetailAllowStatus() == EXAMINE_STATUS_PASS || detail.getDetailAllowStatus() == EXAMINE_STATUS_FORCED_FINISH) {
                                        stringBuilder.append("审批状态：同意").append("\n");
                                    } else {
                                        stringBuilder.append("审批状态：拒绝").append("\n");
                                    }

                                    if (isNullOrEmpty(detail.getDetailAllowOption())) {
                                        stringBuilder.append("审批意见：").append("\n");
                                    } else {
                                        stringBuilder.append("审批意见：").append(detail.getDetailAllowOption()).append("\n");
                                    }

                                    if (isNullOrEmpty(detail.getDetailAllowTime())) {
                                        stringBuilder.append("审批时间：").append("\n");
                                    } else {
                                        stringBuilder.append("审批时间：").append(TimeUtil.DateHanZiSimpleFormat(detail.getDetailAllowTime()))
                                                .append("\n").append("\n");
                                    }
                                    sort++;
                                }
                            }
                            row1.createCell(header.length + 1).setCellValue(new HSSFRichTextString(stringBuilder.toString()));

                        }
                    }
                }
            }

//            response.reset();
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("维修报审记录导出表.xlsx", "utf-8"));
            response.setCharacterEncoding("utf-8");
            response.setHeader("file-type", "download");
            response.setHeader("file-name", URLEncoder.encode("维修报审记录导出表.xlsx", "utf-8"));
            response.setHeader("Access-Control-Expose-Headers", "file-type,file-name");
//            //刷新缓冲
            response.flushBuffer();
            //workbook将Excel写入到response的输出流中，供页面下载
            OutputStream os = response.getOutputStream();
            workbook.write(os);

            workbook.close();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
            return new AsyncResult<>(CommonResult.failed(CommonCodeEnum.FAIL));
        }
        return null;
    }



    private void addProcessTableHead(HSSFRow headRow, HSSFCellStyle headerStyle, Integer origin_cell_num, String originHeadContent) {
        Integer cell_num = origin_cell_num;

        setTableHead(headRow, headerStyle, cell_num++, originHeadContent + "审批人");
        setTableHead(headRow, headerStyle, cell_num++, originHeadContent + "审批时间");
        setTableHead(headRow, headerStyle, cell_num++, originHeadContent + "审批状态");
        setTableHead(headRow, headerStyle, cell_num, originHeadContent + "审批意见");

    }

    private void setTableHead(HSSFRow headRow, HSSFCellStyle headerStyle, Integer cell_num, String headContent) {
        HSSFCell cell = headRow.createCell(cell_num);
        //创建一个内容对象
        HSSFRichTextString text = new HSSFRichTextString(headContent);

        //将内容对象的文字内容写入到单元格中
        cell.setCellValue(text);
        cell.setCellStyle(headerStyle);
    }

    @Override
    @Transactional
    public ResponseResult forcedFinishRepairCheck(String applyId, String userId) {
        //校验数据
        if (isNullOrEmpty(applyId)) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        SmsRepairCheckApply smsRepairCheckApply = smsRepairCheckApplyMapper.selectById(applyId);
        if(isNullOrEmpty(smsRepairCheckApply)){
            return CommonResult.failed(CommonCodeEnum.REPAIR_CHECK_NOT_EXIST);
        }
        if(smsRepairCheckApply.getAllowStatus() != REPAIR_CHECK_STATUS_WAIT_ALLOW){
            return CommonResult.failed(CommonCodeEnum.REPAIR_CHECK_NOT_FORCED);
        }
        //修改审批表状态为通过
        smsRepairCheckApply.setAllowStatus(REPAIR_CHECK_STATUS_PASS);
        smsRepairCheckApply.setEndTime(new Date());
        smsRepairCheckApplyMapper.updateById(smsRepairCheckApply);

        //修改节点为强制归档
        SmsRepairCheckDetail smsRepairCheckDetail = new SmsRepairCheckDetail();
        smsRepairCheckDetail.setDetailAllowStatus(REPAIR_CHECK_STATUS_FORCED_FINISH);
        smsRepairCheckDetail.setDetailAllowUserId(userId);
        smsRepairCheckDetail.setDetailAllowTime(new Date());
        smsRepairCheckDetailMapper.update(smsRepairCheckDetail,new LambdaQueryWrapper<SmsRepairCheckDetail>()
                .eq(SmsRepairCheckDetail::getApplicationId,applyId)
                .eq(SmsRepairCheckDetail::getDetailAllowStatus,REPAIR_CHECK_STATUS_WAIT_ALLOW));

        //消息通知
        newTipsUtil.cancelFinishTips(applyId);

        return CommonResult.success();
    }

    @Override
    @Transactional
    public ResponseResult forcedTorsionPayment(SmsRepairCheckDetailTorsionVO torsionVO) {
        if(isNullOrEmpty(torsionVO.getDetailId(),torsionVO.getApplyId(),torsionVO.getProcessObjectType(),torsionVO.getProcessObjectId())){
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        SmsRepairCheckApply smsRepairCheckApply = smsRepairCheckApplyMapper.selectById(torsionVO.getApplyId());
        if(isNullOrEmpty(smsRepairCheckApply)){
            return CommonResult.failed(CommonCodeEnum.REPAIR_CHECK_NOT_EXIST);
        }
        SmsRepairCheckDetail detail = smsRepairCheckDetailMapper.selectById(torsionVO.getDetailId());
        if(isNullOrEmpty(detail)){
            return CommonResult.failed(CommonCodeEnum.REPAIR_CHECK_NOT_TORSION);
        }
        if(detail.getDetailAllowStatus() != REPAIR_CHECK_STATUS_WAIT_ALLOW){
            return CommonResult.failed(CommonCodeEnum.REPAIR_CHECK_DETAIL_NOT_FORCED);
        }
        detail.setProcessObjectType(torsionVO.getProcessObjectType());
        detail.setProcessObjectId(torsionVO.getProcessObjectId());
        smsRepairCheckDetailMapper.updateById(detail);
        //消息通知
        //判断第一节点直接发消息,其他要前节点审批后才发该节点通知
        boolean flag = true;
        if(!detail.getDetailSort().equals(1)){
            SmsRepairCheckDetail beforeDetail = smsRepairCheckDetailMapper.selectOne(new LambdaQueryWrapper<SmsRepairCheckDetail>()
                    .eq(SmsRepairCheckDetail::getApplicationId, torsionVO.getApplyId())
                    .eq(SmsRepairCheckDetail::getDetailSort, detail.getDetailSort() - 1));
            if(beforeDetail.getDetailAllowStatus() != EXAMINE_STATUS_PASS){
                flag = false;
            }
        }
        if(flag) {
            RangeTypeEnum rangeTypeEnum;
            if (detail.getProcessObjectType() == AGREEMENT_OBJECT_TYPE_PERSON) {
                rangeTypeEnum = RangeTypeEnum.RANGE_TYPE_ENUM_PERSON;
            } else {
                rangeTypeEnum = RangeTypeEnum.RANGE_TYPE_ENUM_ROLE;
            }
            List<String> rangeList = new ArrayList<>();
            rangeList.add(detail.getProcessObjectId());
            newTipsUtil.allowContinueTips(torsionVO.getApplyId(),
                    null,
                    rangeTypeEnum,
                    rangeList,
                    detail.getId());
        }
        return CommonResult.success();
    }

    @Override
    @Transactional
    public ResponseResult replaceApplyRepairCheck(String userId, SmsRepairCheckApplyAllowVO allowVO) {
        if (isNullOrEmpty(allowVO.getApplyId())
//                || isNullOrEmpty(allowVO.getDetailAllowStatus()
        ) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        if (allowVO.getDetailAllowStatus() != REPAIR_CHECK_STATUS_PASS
                && allowVO.getDetailAllowStatus() != REPAIR_CHECK_STATUS_DENY) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        SmsRepairCheckDetail applicationDetail;
        applicationDetail =
                smsRepairCheckDetailMapper.selectOne(new QueryWrapper<SmsRepairCheckDetail>()
                        .lambda()
                        .eq(SmsRepairCheckDetail::getApplicationId, allowVO.getApplyId())
                        .eq(SmsRepairCheckDetail::getId, allowVO.getDetailId())
                        .eq(SmsRepairCheckDetail::getDetailAllowStatus, REPAIR_CHECK_STATUS_WAIT_ALLOW));
        if (isNullOrEmpty(applicationDetail)) {
            return CommonResult.failed(CommonCodeEnum.REPAIR_CHECK_ALLOW_FAIL);
        }
        //历史数据问题
        if(isNullOrEmpty(applicationDetail.getProcessObjectType())){
            applicationDetail = smsRepairCheckDetailMapper.selectOne(new QueryWrapper<SmsRepairCheckDetail>()
                    .lambda()
                    .eq(SmsRepairCheckDetail::getApplicationId, allowVO.getApplyId())
                    .eq(SmsRepairCheckDetail::getDetailSort, applicationDetail.getDetailSort() + 1));
        }

        if (!applicationDetail.getDetailSort().equals(1)) {
            SmsRepairCheckDetail preDetail =
                    smsRepairCheckDetailMapper.selectOne(new QueryWrapper<SmsRepairCheckDetail>()
                            .lambda()
                            .eq(SmsRepairCheckDetail::getApplicationId, allowVO.getApplyId())
                            .eq(SmsRepairCheckDetail::getDetailSort, applicationDetail.getDetailSort() - 1));
            if (preDetail != null && !isNullOrEmpty(preDetail.getId())) {
                if (preDetail.getDetailAllowStatus() != REPAIR_CHECK_STATUS_PASS) {
                    return CommonResult.failed(CommonCodeEnum.REPAIR_CHECK_ALLOW_FAIL);
                }
            }
        }

        //判断是否后勤处，后勤处指定检修人
        if (applicationDetail.getProcessName().equals(PROCESS_NAME_LOGISTICS) && allowVO.getDetailAllowStatus() == REPAIR_CHECK_STATUS_PASS) {
            //校验检修人是否传了
            if (isNullOrEmpty(allowVO.getProcessCheckId())) {
                ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.REPAIR_CHECK_NOT_FIND));
            }
            SmsRepairCheckApply apply = new SmsRepairCheckApply();
            apply.setId(allowVO.getApplyId());
            apply.setApplyBadReason(allowVO.getApplyBadReason());
            smsRepairCheckApplyMapper.updateById(apply);
            //检修人节点修改
            SmsRepairCheckDetail detail = new SmsRepairCheckDetail();
            detail.setProcessObjectId(allowVO.getProcessCheckId());
            detail.setProcessObjectType(REPAIR_CHECK_OBJECT_TYPE_PERSON);
            smsRepairCheckDetailMapper.update(detail,new LambdaQueryWrapper<SmsRepairCheckDetail>()
                    .eq(SmsRepairCheckDetail::getApplicationId,allowVO.getApplyId())
                    .eq(SmsRepairCheckDetail::getProcessName,PROCESS_NAME_MAINTENANCE));

        }
        if (applicationDetail.getProcessName().equals(PROCESS_NAME_MAINTENANCE) && allowVO.getDetailAllowStatus() == REPAIR_CHECK_STATUS_PASS) {
            SmsRepairCheckApply apply = new SmsRepairCheckApply();
            apply.setId(allowVO.getApplyId());
            apply.setApplyFixedTime(new Date());
//            apply.setApplyBadReason(allowVO.getApplyBadReason());
            apply.setApplyFixedResult(allowVO.getApplyFixedResult());
            apply.setApplyFixedPhone(allowVO.getApplyFixedPhone());
            apply.setApplyHandleOption(allowVO.getApplyHandleOption());
            apply.setApplyCompensationAmount(allowVO.getApplyCompensationAmount());
            smsRepairCheckApplyMapper.updateById(apply);



        }

        if (applicationDetail.getProcessName().equals(PROCESS_NAME_MAINTENANCE_CONFIRMATION)) {
            SmsRepairCheckDetail detail = new SmsRepairCheckDetail();
//            detail.setApplicationId(allowVO.getApplyId());
            QueryWrapper<SmsRepairCheckApply> queryWrapper3 = new QueryWrapper<>();
            queryWrapper3.lambda().eq(SmsRepairCheckApply::getId, allowVO.getApplyId());
            SmsRepairCheckApply apply1 = smsRepairCheckApplyMapper.selectOne(queryWrapper3);
            detail.setProcessObjectId(apply1.getApplyUserId());
//            detail.setProcessName("报修人");
            detail.setProcessObjectType(REPAIR_CHECK_OBJECT_TYPE_PERSON);
//            detail.setDetailSort(applicationDetail.getDetailSort() + 1);
            smsRepairCheckDetailMapper.update(detail,new LambdaQueryWrapper<SmsRepairCheckDetail>()
                    .eq(SmsRepairCheckDetail::getApplicationId,allowVO.getApplyId())
                    .eq(SmsRepairCheckDetail::getProcessName,PROCESS_NAME_REPAIR));
        }
        SmsRepairCheckDetail allowDetail = new SmsRepairCheckDetail();
        allowDetail.setId(allowVO.getDetailId());
        allowDetail.setDetailAllowStatus(allowVO.getDetailAllowStatus());
        if (!isNullOrEmpty(allowVO.getDetailAllowOpinion())) {
            allowDetail.setDetailAllowOption(allowVO.getDetailAllowOpinion());
        }
        Date nowDate = new Date();
        allowDetail.setDetailAllowTime(nowDate);
        allowDetail.setDetailAllowUserId(userId);
        allowDetail.setDetailAllowSign(allowVO.getDetailAllowSign());
        allowDetail.setDetailAllowStamp(allowVO.getDetailAllowStamp());
        smsRepairCheckDetailMapper.updateById(allowDetail);

        boolean is_done = false;

        //判断是否最后一个节点 是否驳回

        Integer detailCount = smsRepairCheckDetailMapper.selectCount(new QueryWrapper<SmsRepairCheckDetail>()
                .lambda()
                .eq(SmsRepairCheckDetail::getApplicationId, allowVO.getApplyId()));

        if (detailCount.equals(applicationDetail.getDetailSort()) || allowVO.getDetailAllowStatus() == REPAIR_CHECK_STATUS_DENY) {
            is_done = true;

            SmsRepairCheckApply updateApplication = new SmsRepairCheckApply();
            updateApplication.setId(allowVO.getApplyId());
            updateApplication.setEndTime(nowDate);
            updateApplication.setAllowStatus(allowVO.getDetailAllowStatus());
            smsRepairCheckApplyMapper.updateById(updateApplication);
        }

        //节点驳回 重置其余节点状态
        if (allowVO.getDetailAllowStatus() == REPAIR_CHECK_STATUS_DENY) {
            SmsRepairCheckDetail updateDenyDetail =
                    new SmsRepairCheckDetail();
            updateDenyDetail.setDetailAllowStatus(REPAIR_CHECK_STATUS_DENY_FINISH);
            smsRepairCheckDetailMapper.update(updateDenyDetail, new QueryWrapper<SmsRepairCheckDetail>()
                    .lambda()
                    .eq(SmsRepairCheckDetail::getApplicationId, allowVO.getApplyId())
                    .eq(SmsRepairCheckDetail::getDetailAllowStatus, REPAIR_CHECK_STATUS_WAIT_ALLOW));
        }


        //消息通知
        if (is_done) {
            boolean result_status = false;
            if (allowVO.getDetailAllowStatus() == REPAIR_CHECK_STATUS_PASS) {
                result_status = true;
            }
            newTipsUtil.allowFinishTips(allowVO.getApplyId(), userId, result_status);
        } else {
            int i = applicationDetail.getDetailSort();

            SmsRepairCheckDetail nextDetail =
                    smsRepairCheckDetailMapper.selectOne(new QueryWrapper<SmsRepairCheckDetail>()
                            .lambda()
                            .eq(SmsRepairCheckDetail::getApplicationId, allowVO.getApplyId())
                            .eq(SmsRepairCheckDetail::getDetailSort, i + 1));
            RangeTypeEnum rangeTypeEnum;
            if (nextDetail.getProcessIsApplicationEdit().equals(1)) {
                rangeTypeEnum = RangeTypeEnum.RANGE_TYPE_ENUM_PERSON;
            } else {
                if (nextDetail.getProcessObjectType() == REPAIR_CHECK_OBJECT_TYPE_ROLE) {
                    rangeTypeEnum = RangeTypeEnum.RANGE_TYPE_ENUM_ROLE;
                } else {
                    rangeTypeEnum = RangeTypeEnum.RANGE_TYPE_ENUM_PERSON;
                }
            }

            List<String> rangeIDList = new ArrayList<>();
            rangeIDList.add(nextDetail.getProcessObjectId());
            newTipsUtil.allowContinueTips(allowVO.getApplyId(),
                    null,
                    rangeTypeEnum,
                    rangeIDList,
                    nextDetail.getId());
        }
        return CommonResult.success();
    }

    @Override
    @Transactional
    public ResponseResult forcedRejectRepairCheck(SmsRepairCheckApplyForceVO forceVO, String userId) {

        if(isNullOrEmpty(forceVO.getApplyId(),forceVO.getDetailAllowOption())){
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        //校验
        SmsRepairCheckApply smsRepairCheckApply = smsRepairCheckApplyMapper.selectById(forceVO.getApplyId());
        if(isNullOrEmpty(smsRepairCheckApply)){
            return CommonResult.failed(CommonCodeEnum.REPAIR_CHECK_NOT_EXIST);
        }
        //总状态为待审批才能强制驳回
        Integer allowStatus = smsRepairCheckApply.getAllowStatus();
        if(allowStatus != REPAIR_CHECK_STATUS_WAIT_ALLOW){
            return CommonResult.failed(CommonCodeEnum.REPAIR_CHECK_NOT_FORCED_REJECT);
        }
        //修改申请表状态为驳回
        smsRepairCheckApply.setAllowStatus(REPAIR_CHECK_STATUS_DENY);
        smsRepairCheckApply.setEndTime(new Date());
        smsRepairCheckApplyMapper.updateById(smsRepairCheckApply);
        //修改节点状态为强制驳回
        SmsRepairCheckDetail smsRepairCheckDetail = new SmsRepairCheckDetail();
        smsRepairCheckDetail.setDetailAllowTime(new Date());
        smsRepairCheckDetail.setDetailAllowUserId(userId);
        smsRepairCheckDetail.setDetailAllowStatus(REPAIR_CHECK_STATUS_FORCED_REJECT);
        smsRepairCheckDetail.setDetailAllowOption(forceVO.getDetailAllowOption());
        smsRepairCheckDetailMapper.update(smsRepairCheckDetail, new LambdaQueryWrapper<SmsRepairCheckDetail>()
                .eq(SmsRepairCheckDetail::getApplicationId, forceVO.getApplyId())
                .eq(SmsRepairCheckDetail::getDetailAllowStatus, REPAIR_CHECK_STATUS_WAIT_ALLOW));
        //消息提醒
        newTipsUtil.cancelFinishTips(forceVO.getApplyId());
        return CommonResult.success();
    }
}
